<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>mario</title>
	<script src="createjs.js"></script>
	<script src="mario.js"></script>
	<script src="ndgmr.Collision.js"></script>
	<script>
		var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;

		function init() {
			canvas = document.getElementById("canvas");
			anim_container = document.getElementById("animation_container");
			dom_overlay_container = document.getElementById("dom_overlay_container");
			var comp = AdobeAn.getComposition("3E43E8665373C141A254E036C6BA9686");
			var lib = comp.getLibrary();
			var loader = new createjs.LoadQueue(false);
			loader.addEventListener("fileload", function (evt) {
				handleFileLoad(evt, comp)
			});
			loader.addEventListener("complete", function (evt) {
				handleComplete(evt, comp)
			});
			var lib = comp.getLibrary();
			loader.loadManifest(lib.properties.manifest);
		}

		function handleFileLoad(evt, comp) {
			var images = comp.getImages();
			if (evt && (evt.item.type == "image")) {
				images[evt.item.id] = evt.result;
			}
		}

		function handleComplete(evt, comp) {
			//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
			var lib = comp.getLibrary();
			var ss = comp.getSpriteSheet();
			var queue = evt.target;
			var ssMetadata = lib.ssMetadata;
			for (i = 0; i < ssMetadata.length; i++) {
				ss[ssMetadata[i].name] = new createjs.SpriteSheet({
					"images": [queue.getResult(ssMetadata[i].name)],
					"frames": ssMetadata[i].frames
				})
			}
			exportRoot = new lib.mario();
			stage = new lib.Stage(canvas);
			//Registers the "tick" event listener.
			fnStartAnimation = function () {
				stage.addChild(exportRoot);

				// ------------------------------------------------------------------

				let loadint = 0;
				const sounds = [{
						src: './assets/bg.mp3',
						id: 'bg'
					},
					{
						src: './assets/boom.mp3',
						id: 'boom'
					},
					{
						src: './assets/coin.mp3',
						id: 'coin'
					},
					{
						src: './assets/play.mp3',
						id: 'play'
					},
				];
				createjs.Sound.alternateExtensions = ['mp3'];
				createjs.Sound.registerSounds(sounds, './');
				createjs.Sound.addEventListener('fileload', e => {
					loadint++;
					if (loadint === sounds.length) {
						document.querySelector('.loading').style.display = 'none';
					}
				});


				const SPEED = 10;
				const ATTACK = 10;
				const MAX_WIDTH = 710;
				const MIN_WIDTH = -10;

				let isStart = false;
				let hp = 120;
				let isKeydown = false;
				let position = 1;
				let count = 0;

				const Gamer = new lib.Gamer();
				Gamer.x = 356;
				Gamer.y = 343;
				exportRoot.addChild(Gamer);

				function keydownHandle(e) {
					if (isKeydown) return;
					if (e.keyCode === 39 || e.keyCode === 37) {
						isKeydown = true;
						position = e.keyCode === 39 ? 1 : -1;
						Gamer.gotoAndPlay('run');
					}
				}

				function keyupHandle(e) {
					isKeydown = false;
					Gamer.gotoAndPlay('stop')
					Gamer.stop();
				}

				let coinTime = setInterval(() => {
					if (!isStart) return;

					const Coin = new lib.Coin();
					Coin.x = Math.random() * (660 - 51) + 50 >> 0;
					Coin.y = -50;
					exportRoot.addChildAt(Coin, 1);

					createjs.Tween.get(Coin)
						.to({
							y: 400
						}, 2500)
						.call(() => {
							exportRoot.removeChild(Coin);
							hp -= ATTACK;
							renderStatus();
						})
						.addEventListener('change', () => {
							const hit = ndgmr.checkRectCollision(Coin, Gamer);
							if (hit) {
								createjs.Tween.removeTweens(Coin);
								exportRoot.removeChild(Coin);
								createjs.Sound.play('coin');
								count++;
								renderStatus();
							}
						})

				}, 1000);

				function renderStatus() {
					document.querySelector('.count').innerHTML = count;
					document.querySelector('.hp').style.width = `${hp}px`;
				}

				function tickHandle(e) {
					if (hp <= 0) {
						Gamer.gotoAndPlay('boom');
						const boomAudio = createjs.Sound.play('boom');
						boomAudio.volume = 0.1;

						clearInterval(coinTime);
						createjs.Ticker.removeEventListener('tick', tickHandle);
						window.removeEventListener('keydown', keydownHandle);
						window.removeEventListener('keyup', keyupHandle);

						document.querySelector('.over').style.display = 'flex';
					}

					if (!isKeydown) return;

					Gamer.scaleX = position;
					Gamer.x += SPEED * position;

					if (Gamer.x >= MAX_WIDTH) {
						Gamer.x = MIN_WIDTH + 1;
					}

					if (Gamer.x <= MIN_WIDTH) {
						Gamer.x = MAX_WIDTH;
					}
				}

				window.addEventListener('keydown', keydownHandle);
				window.addEventListener('keyup', keyupHandle);
				createjs.Ticker.addEventListener('tick', tickHandle);

				function startGame() {
					isStart = true;
					document.querySelector('.paly').style.display = 'none';
					createjs.Sound.play('play');

					const bgAudio = createjs.Sound.play('bg', {
						loop: -1
					});
					bgAudio.volume = 0.1;
				}

				document.querySelector('.paly').addEventListener('click', startGame);
				document.querySelector('.over').addEventListener('click', () => {
					window.location.reload();
				});


				// ------------------------------------------------------------------

				createjs.Ticker.setFPS(lib.properties.fps);
				createjs.Ticker.addEventListener("tick", stage)
				stage.addEventListener("tick", handleTick)

				function getProjectionMatrix(container, totalDepth) {
					var focalLength = 528.25;
					var projectionCenter = {
						x: lib.properties.width / 2,
						y: lib.properties.height / 2
					};
					var scale = (totalDepth + focalLength) / focalLength;
					var scaleMat = new createjs.Matrix2D;
					scaleMat.a = 1 / scale;
					scaleMat.d = 1 / scale;
					var projMat = new createjs.Matrix2D;
					projMat.tx = -projectionCenter.x;
					projMat.ty = -projectionCenter.y;
					projMat = projMat.prependMatrix(scaleMat);
					projMat.tx += projectionCenter.x;
					projMat.ty += projectionCenter.y;
					return projMat;
				}

				function handleTick(event) {
					var cameraInstance = exportRoot.___camera___instance;
					if (cameraInstance !== undefined && cameraInstance.pinToObject !== undefined) {
						cameraInstance.x = cameraInstance.pinToObject.x + cameraInstance.pinToObject.pinOffsetX;
						cameraInstance.y = cameraInstance.pinToObject.y + cameraInstance.pinToObject.pinOffsetY;
						if (cameraInstance.pinToObject.parent !== undefined && cameraInstance.pinToObject.parent.depth !==
							undefined)
							cameraInstance.depth = cameraInstance.pinToObject.parent.depth + cameraInstance.pinToObject.pinOffsetZ;
					}
					applyLayerZDepth(exportRoot);
				}

				function applyLayerZDepth(parent) {
					var cameraInstance = parent.___camera___instance;
					var focalLength = 528.25;
					var projectionCenter = {
						'x': 0,
						'y': 0
					};
					if (parent === exportRoot) {
						var stageCenter = {
							'x': lib.properties.width / 2,
							'y': lib.properties.height / 2
						};
						projectionCenter.x = stageCenter.x;
						projectionCenter.y = stageCenter.y;
					}
					for (child in parent.children) {
						var layerObj = parent.children[child];
						if (layerObj == cameraInstance)
							continue;
						applyLayerZDepth(layerObj, cameraInstance);
						if (layerObj.layerDepth === undefined)
							continue;
						if (layerObj.currentFrame != layerObj.parent.currentFrame) {
							layerObj.gotoAndPlay(layerObj.parent.currentFrame);
						}
						var matToApply = new createjs.Matrix2D;
						var cameraMat = new createjs.Matrix2D;
						var totalDepth = layerObj.layerDepth ? layerObj.layerDepth : 0;
						var cameraDepth = 0;
						if (cameraInstance && !layerObj.isAttachedToCamera) {
							var mat = cameraInstance.getMatrix();
							mat.tx -= projectionCenter.x;
							mat.ty -= projectionCenter.y;
							cameraMat = mat.invert();
							cameraMat.prependTransform(projectionCenter.x, projectionCenter.y, 1, 1, 0, 0, 0, 0, 0);
							cameraMat.appendTransform(-projectionCenter.x, -projectionCenter.y, 1, 1, 0, 0, 0, 0, 0);
							if (cameraInstance.depth)
								cameraDepth = cameraInstance.depth;
						}
						if (layerObj.depth) {
							totalDepth = layerObj.depth;
						}
						//Offset by camera depth
						totalDepth -= cameraDepth;
						if (totalDepth < -focalLength) {
							matToApply.a = 0;
							matToApply.d = 0;
						} else {
							if (layerObj.layerDepth) {
								var sizeLockedMat = getProjectionMatrix(parent, layerObj.layerDepth);
								if (sizeLockedMat) {
									sizeLockedMat.invert();
									matToApply.prependMatrix(sizeLockedMat);
								}
							}
							matToApply.prependMatrix(cameraMat);
							var projMat = getProjectionMatrix(parent, totalDepth);
							if (projMat) {
								matToApply.prependMatrix(projMat);
							}
						}
						layerObj.transformMatrix = matToApply;
					}
				}
			}
			//Code to support hidpi screens and responsive scaling.
			function makeResponsive(isResp, respDim, isScale, scaleType) {
				var lastW, lastH, lastS = 1;
				window.addEventListener('resize', resizeCanvas);
				resizeCanvas();

				function resizeCanvas() {
					var w = lib.properties.width,
						h = lib.properties.height;
					var iw = window.innerWidth,
						ih = window.innerHeight;
					var pRatio = window.devicePixelRatio || 1,
						xRatio = iw / w,
						yRatio = ih / h,
						sRatio = 1;
					if (isResp) {
						if ((respDim == 'width' && lastW == iw) || (respDim == 'height' && lastH == ih)) {
							sRatio = lastS;
						} else if (!isScale) {
							if (iw < w || ih < h)
								sRatio = Math.min(xRatio, yRatio);
						} else if (scaleType == 1) {
							sRatio = Math.min(xRatio, yRatio);
						} else if (scaleType == 2) {
							sRatio = Math.max(xRatio, yRatio);
						}
					}
					canvas.width = w * pRatio * sRatio;
					canvas.height = h * pRatio * sRatio;
					canvas.style.width = dom_overlay_container.style.width = anim_container.style.width = w * sRatio + 'px';
					canvas.style.height = anim_container.style.height = dom_overlay_container.style.height = h * sRatio + 'px';
					stage.scaleX = pRatio * sRatio;
					stage.scaleY = pRatio * sRatio;
					lastW = iw;
					lastH = ih;
					lastS = sRatio;
					stage.tickOnUpdate = false;
					stage.update();
					stage.tickOnUpdate = true;
				}
			}
			makeResponsive(false, 'both', false, 1);
			AdobeAn.compositionLoaded(lib.properties.id);
			fnStartAnimation();
		}
	</script>
	<style>
		body {
			margin: 0;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100vh;
		}

		#animation_container {
			position: relative;
		}

		.count {
			position: absolute;
			top: 0;
			left: 30px;
			font-size: 30px;
			color: #fff;
			z-index: 10;
		}

		.hpWapper {
			position: absolute;
			right: 30px;
			top: 30px;
			font-size: 20px;
			z-index: 10;
			font-weight: bold;
		}

		.hpbox {
			position: relative;
			display: inline-block;
			width: 120px;
			height: 18px;
			border: 3px solid #000;
			vertical-align: -4px;
			background: #fff;
		}

		.hp {
			position: absolute;
			top: 0;
			left: 0;
			background: #f8f901;
			width: 100%;
			height: 100%;
		}

		.over,
		.paly {
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			cursor: pointer;
			z-index: 100;
		}
	</style>
</head>

<body onload="init();">

	<div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:700px; height:400px">
		<div class="loading"></div>

		<div class="over" style="display: none;">
			<img src="./assets/gameover.png" alt="gameover">
		</div>
		<div class="paly">
			<img src="./assets/play.png" alt="play">
		</div>

		<h1 class="count">0</h1>
		<div class="hpWapper">
			HP <div class="hpbox">
				<div class="hp"></div>
			</div>
		</div>

		<canvas id="canvas" width="700" height="400"
			style="position: absolute; display: block; background-color:rgba(255, 255, 255, 1.00);"></canvas>
		<div id="dom_overlay_container"
			style="pointer-events:none; overflow:hidden; width:700px; height:400px; position: absolute; left: 0px; top: 0px; display: block;">
		</div>
	</div>
</body>

</html>